/* eslint-disable no-undef,import/first */
import { routerRedux } from 'dva/router';
import * as config from '../utils/config';
import * as utils from '../utils/utils';
import * as services from '../services/services';
import { message } from 'antd';

if (location.pathname === '/' || location.pathname === '/login') {
  localStorage.clear();
}

export default {
  namespace: 'app',
  state: {
    token: JSON.parse(localStorage.getItem(`${config.prefix}token`)) || {},
    userinfo: JSON.parse(localStorage.getItem(`${config.prefix}userinfo`)) || {},
    commonConst: JSON.parse(localStorage.getItem(`${config.prefix}commonConst`)) || [],
    systemData: JSON.parse(localStorage.getItem(`${config.prefix}systemData`)) || {},
    dateFormat: JSON.parse(localStorage.getItem(`${config.prefix}dateFormat`)) || '',
    panes: JSON.parse(localStorage.getItem(`${config.prefix}panes`)) || [
      {
        paneType: 'home', title: '主页', route: '/indexPage', key: '1',
      },
    ],
    ppopupPane: {},
    secondppopupPane: {},
    currentPane: JSON.parse(localStorage.getItem(`${config.prefix}currentPane`)) || { key: '1' },
    decimals: JSON.parse(localStorage.getItem(`${config.prefix}decimals`)) || '',
    comParameter: [], /* 常用操作 */
    modelCenter: {}, /* KPI工作中心 */
  },
  reducers: {
    saveToken(state, { payload: token }) {
      localStorage.setItem(`${config.prefix}token`, JSON.stringify(token));
      return { ...state, token };
    },
    saveCommonConst(state, { payload: commonConst }) {
      localStorage.setItem(`${config.prefix}commonConst`, JSON.stringify(commonConst));
      return { ...state, commonConst };
    },
    saveUserinfo(state, { payload: userinfo }) {
      localStorage.setItem(`${config.prefix}userinfo`, JSON.stringify(userinfo));
      return { ...state, userinfo };
    },
    saveSystemData(state, { payload: systemData }) {
      localStorage.setItem(`${config.prefix}systemData`, JSON.stringify(systemData));
      return { ...state, systemData };
    },
    saveDecimals(state, { payload: decimals }) {
      localStorage.setItem(`${config.prefix}decimals`, JSON.stringify(decimals));
      return { ...state, decimals };
    },
    saveDateFormat(state, { payload: dateFormat }) {
      localStorage.setItem(`${config.prefix}dateFormat`, JSON.stringify(dateFormat));
      return { ...state, dateFormat };
    },
    savePanes(state, { payload: { panes } }) {
      localStorage.setItem(`${config.prefix}panes`, JSON.stringify(panes));
      return { ...state, panes };
    },
    saveppopupPane(state, { payload: { ppopupPane } }) {
      return { ...state, ppopupPane };
    },
    saveSecondPpopupPane(state, { payload: { secondppopupPane } }) {
      return { ...state, secondppopupPane };
    },
    setCurrentPane(state, { payload: { currentPane } }) {
      localStorage.setItem(`${config.prefix}currentPane`, JSON.stringify(currentPane));
      return { ...state, currentPane };
    },
    /*   当前页和页数一起添加   */
    savePanesAndCurrentPane(state, { payload: { panes, currentPane } }) {
      localStorage.setItem(`${config.prefix}panes`, JSON.stringify(panes));
      localStorage.setItem(`${config.prefix}currentPane`, JSON.stringify(currentPane));
      return { ...state, panes, currentPane };
    },
    saveComParameter(state, { payload: { comParameter } }) {
      return { ...state, comParameter };
    },
    saveModelCenter(state, { payload: { modelCenter } }) {
      return { ...state, modelCenter };
    },
  },
  effects: {
    /**   修改页签   */
    *changePaneData({ payload }, { put, select }) {
      /*   待用数据赋值   */
      const {
        parentId, /*   父页面编号   */
        showRender, /*   主表渲染对象   */
        showSlaveRender, /*   从表渲染对象   */
        editTableRender, /*   从表渲染控制   */
        isRender, /*   是否从高阶渲染   */
        isRenderPart, /*   是否进行部分渲染   */
      } = payload; /*   参数接收   */
      /*   过滤出需要change的pane   */
      const panes = yield select(state => state.app.panes);
      const index = panes.findIndex(item => item.key === parentId);
      /*   父页签存在则进行变更,否则不需要改变什么   */
      if (index >= 0) {
        /*   页签数据变更   */
        const pane = panes[index];
        pane.showRender = showRender;
        pane.showSlaveRender = showSlaveRender;
        pane.editTableRender = editTableRender;
        pane.isRender = isRender;
        pane.isRenderPart = isRenderPart;
        /*   保存页签   */
        yield put({
          type: 'savePanes',
          payload: {
            panes,
          },
        });
      }
    },
    /**   添加页签   */
    *addNewPane({ payload }, { put, select }) {
      /*   先获取所有的页签   */
      const panes = yield select(state => state.app.panes);
      /*   判断页签存储个数是否超过容量   */
      if (utils.isNotEmptyArr(panes) && panes.length === config.maxTabSize) {
        throw new Error('Tab数量已超过限制，无法新增！');
      }
      /*   获取需要新增的页签   */
      const { pane } = payload;
      /*   判断是否添加页签的条件   */
      const index = panes.findIndex(temp => temp.key === pane.key);
      /*   满足添加条件就添加页签   */
      if (index < 0) {
        panes.push(pane);
        yield put({
          type: 'savePanesAndCurrentPane',
          payload: {
            panes,
            currentPane: pane,
          },
        });
        yield put(routerRedux.push(pane.route));
      }
    },
    *addPane({ payload }, { put, select }) {
      const panes = yield select(state => state.app.panes);
      if (panes.length === config.maxTabSize) {
        throw new Error('Tab数量已超过限制，无法新增！');
      }
      const { pane } = payload;
      yield put({ type: 'saveCurrentPane', payload: { currentPane: pane } });
      const tempPanes = panes.filter(temp => temp.key === pane.key);
      if (tempPanes.length === 0) {
        panes.push(pane);
      }
      yield put({ type: 'savePanes', payload: { panes } });
    },
    *addppopupPane({ payload }, { put }) {
      const { pane } = payload;
      yield put({ type: 'saveppopupPane', payload: { ppopupPane: pane } });
    },
    *changePpopupPane({ payload }, { put, select }) {
      const ppopupPane = yield select(state => state.app.ppopupPane);
      const { resultValue } = payload;
      yield put({ type: 'saveppopupPane', payload: { ppopupPane: { ...ppopupPane, resultValue } } });
    },
    *removeModalPane({ payload }, { put }) {
      const panes = payload.changePanes;
      yield put({ type: 'saveppopupPane', payload: { panes } });
    },
    *addSecondPpopupPane({ payload }, { put }) {
      const { pane } = payload;
      yield put({ type: 'saveSecondPpopupPane', payload: { secondppopupPane: pane } });
    },
    *changeSecondPpopupPane({ payload }, { put, select }) {
      const secondppopupPane = yield select(state => state.app.secondppopupPane);
      const { resultValue } = payload;
      yield put({ type: 'saveSecondPpopupPane', payload: { secondppopupPane: { ...secondppopupPane, resultValue } } });
    },
    *removeSecondModalPane({ payload }, { put }) {
      const panes = payload.changePanes;
      yield put({ type: 'saveSecondPpopupPane', payload: { panes } });
    },
    *removePane({ payload }, { put }) {
      const panes = payload.changePanes;
      const { currentPane } = payload;
      yield put({ type: 'savePanes', payload: { panes } });
      if (panes.length > 0) {
        yield put({ type: 'saveCurrentPane', payload: { currentPane } });
      }
    },
    *saveCurrentPane({ payload }, { put }) {
      const { currentPane } = payload;
      yield put({ type: 'setCurrentPane', payload: { currentPane } });
      yield put(routerRedux.push(currentPane.route));
    },
    *throwError({ payload }, { put }) {
      const { code, msg } = payload;
      if (code === -2) {
        yield put(routerRedux.push('login'));
        throw new Error(msg);
      } else {
        throw new Error(msg);
      }
    },
    *loginOut({ payload }, { call, put, select }) {
      const { url } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.getService, token, url);
      if (data.code === 1) {
        yield put(routerRedux.push('login'));
      } else {
        yield put({ type: 'app/throwError', payload: data });
      }
    },
    *editUser({ payload }, { call, put, select }) {
      const { url, value } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        const userinfo = yield select(state => state.app.userinfo);
        userinfo.sUserName = value.sUserName;
        yield put({ type: 'saveUserinfo', payload: userinfo });
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *editPwd({ payload }, { call, put, select }) {
      const { url, value } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        yield put(routerRedux.push('login'));
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *resetPwd({ payload }, { call, put, select }) {
      const { url, value } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        yield put(routerRedux.push('login'));
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *getAddParameter({ payload }, { call, put, select }) {
      const { url, value } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        const newData = data.dataset.rows[0];
        document.getElementById(newData.sFormId).classList.add('selected');
        const comParameter = yield select(state => state.app.comParameter);
        comParameter.push(newData);
        yield put({ type: 'saveComParameter', payload: { comParameter } });
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *getDelParameter({ payload }, { call, put, select }) {
      const { url, value } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        const delData = data.dataset.rows[0];
        if (document.getElementById(delData.sFormId) !== null) {
          document.getElementById(delData.sFormId).classList.remove('selected');
        } else {
          const urls = `${config.server_host}business/getBuMenu?sModelsId=100`;
          yield put({ type: 'menuPanel/getMenuPanel', payload: { url: urls } });
        }
        const comParameter = yield select(state => state.app.comParameter);
        const index = comParameter.findIndex(item => item.sFormId === delData.sFormId);
        comParameter.splice(index, 1);
        yield put({ type: 'saveComParameter', payload: { comParameter } });
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *getComParameter({ payload }, { call, put, select }) {
      const { url } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.getService, token, url);
      if (data.code === 1) {
        const comParameter = data.dataset.rows;
        yield put({ type: 'saveComParameter', payload: { comParameter } });
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    *getModelCenter({ payload }, { call, put, select }) {
      const { value, url } = payload;
      const token = yield select(state => state.app.token);
      const { data } = yield call(services.postValueService, token, value, url);
      if (data.code === 1) {
        const modelCenter = data.dataset.rows[0];
        yield put({ type: 'saveModelCenter', payload: { modelCenter } });
      } else {
        yield put({ type: 'throwError', payload: data });
      }
    },
    /**   返回新页签   */
    *backPane({ payload }, { put }) {
      const { panes, currentPane } = payload;
      yield put({ type: 'savePanes', payload: { panes } });
      yield put({ type: 'saveCurrentPane', payload: { currentPane } });
    },
  },
  subscriptions: {},
};
